<script setup>
import { ref, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addTaskApi } from '@/api/stocktaking/task'
import InventoryDisplay from './InventoryDisplay.vue'
import { addTaskDetailsApi } from '@/api/stocktaking/taskdetails'
import { getWarehouseApi, getwWrehouseAreaApi, getWarehouseAreaLocalApi } from '@/api/warehousingentry/warehousing'
// 假设后续会创建API文件
// import { addApi, updateApi } from '@/api/stocktaking/task'

const emit = defineEmits(['refresh'])

const dialogVisible = ref(false)
const isViewMode = ref(false)

const dialogFormData = ref({
  id: null,
  taskName: null,
  cronExpression: null,
  startTime: null,
  category: null,
  empId: null,
  isEnable: 1,
  saasId: null,
  createBy: null,
  updateBy: null,
  isDel: 1
})

// 盘点类型选项
const categoryOptions = [
  { value: null, label: '请选择盘点类型' },
  { value: 1, label: '仓库盘点' },
  { value: 2, label: '库区盘点' },
  { value: 3, label: '库位盘点' }
]
const getDialogTitle = () => {
  const map = {
    1: '仓库盘点',
    2: '库区盘点',
    3: '库位盘点'
  }
  return map[dialogFormData.value.category] || '库存信息'
}
// 表单验证规则
const rules = {
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  cronExpression: [
    { required: true, message: '请输入执行时间表达式', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择任务执行时间', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择盘点类型', trigger: 'change' }
  ]
}
// 新增：用于存储获取到的数据
const inventoryData = ref([])

// 监听 category 变化，自动请求对应数据并打开弹窗
watch(
  () => dialogFormData.value.category,
  async (newCategory) => {
    if (!newCategory) return

    try {
      let res
      switch (newCategory) {
        case 1: // 仓库盘点
          res = await getWarehouseApi()
          break
        case 2: // 库区盘点
          res = await getwWrehouseAreaApi()
          break
        case 3: // 库位盘点
          res = await getWarehouseAreaLocalApi()
          break
        default:
          return
      }

      // 统一处理返回数据，转换为通用格式
      // const formattedData = res
      const formattedData = formatInventoryData(res || [])
      console.log('formattedData', formattedData)
      // 更新数据并打开弹窗
      inventoryData.value = formattedData
      inventoryDisplayRef.value.open()
    } catch (error) {
      ElMessage.error('获取数据失败')
    }
  }
)
// 格式化不同接口返回的数据为统一结构
const formatInventoryData = (data) => {
  // return data.map(item => ({
  //   id: item.id,
  //   warehouseName: item.warehouseName || item.name || '',
  //   areaName: item.areaName || item.name || '',
  //   locationCode: item.locationCode || item.code || '',
  //   commodityCode: item.commodityCode || item.specCode || '',
  //   name: item.name || item.title || '',
  //   availableQuantity: item.availableQuantity || item.count || 0,
  //   quantity: 0 // 分配数量初始化为0
  // }))
  return data.map(item => ({
    id: dialogFormData.value.category == 1 ? item.warehouseId :
      dialogFormData.value.category == 2 ? item.warehouseAreaId :
        dialogFormData.value.category == 3 ? item.warehouseAreaLocaId : null,
    name: dialogFormData.value.category == 1 ? item.warehouseName :
      dialogFormData.value.category == 2 ? item.warehouseAreaName :
        dialogFormData.value.category == 3 ? item.warehouseAreaLocaLocaCode : null,
    goodName: item.skuTitle,
    price: item.price,
    commodityCode: item.commodityCode || item.specCode || '',
    availableQuantity: item.availableQuantity || item.count || 0,
    quantity: 0 // 分配数量初始化为0
  }))
}
// 新增：弹窗引用
const inventoryDisplayRef = ref(null)

// 新增：查询库存数据的方法
const queryInventory = async () => {
  try {
    const res = await queryInventoryApi(1, 10, {
      // 可以传入筛选条件，比如任务ID、盘点类型等
      taskId: dialogFormData.value.id,
      category: dialogFormData.value.category
    })
    if (res.code === 200) {
      inventoryDisplayRef.value.open()
      inventoryDisplayRef.value.inventoryData = res.data.rows || []
    } else {
      ElMessage.error('获取库存失败')
    }
  } catch (error) {
    ElMessage.error('请求异常')
  }
}
// 添加模板方法
const setTemplate = (type) => {
  switch (type) {
    case '每天凌晨':
      selectedTime.value = {
        minute: '0',
        hour: '0',
        day: '*',
        month: '*',
        weekday: '*'
      }
      break
    case '每天中午':
      selectedTime.value = {
        minute: '0',
        hour: '12',
        day: '*',
        month: '*',
        weekday: '*'
      }
      break
    case '每周日':
      selectedTime.value = {
        minute: '0',
        hour: '0',
        day: '*',
        month: '*',
        weekday: '0'
      }
      break
    case '每月1号':
      selectedTime.value = {
        minute: '0',
        hour: '0',
        day: '1',
        month: '*',
        weekday: '*'
      }
      break
    case '每小时':
      selectedTime.value = {
        minute: '0',
        hour: '*',
        day: '*',
        month: '*',
        weekday: '*'
      }
      break
    case '每3小时':
      selectedTime.value = {
        minute: '0',
        hour: '*/3',
        day: '*',
        month: '*',
        weekday: '*'
      }
      break
  }
}
// 重置表单
const resetForm = () => {
  dialogVisible.value = false
  isViewMode.value = false
  dialogFormData.value = {
    id: null,
    taskName: null,
    cronExpression: null,
    startTime: null,
    category: null,
    empId: null,
    isEnable: 1,
    saasId: null,
    createBy: null,
    updateBy: null,
    isDel: 1
  }
}
// 添加状态变量
const cronGeneratorVisible = ref(false)
const selectedTime = ref({
  minute: '0',
  hour: '0',
  day: '*',
  month: '*',
  weekday: '*'
})

// 打开Cron生成器
const openCronGenerator = () => {
  cronGeneratorVisible.value = true
}

// 生成Cron表达式
const generateCron = () => {
  const cron = `${selectedTime.value.minute} ${selectedTime.value.hour} ${selectedTime.value.day} ${selectedTime.value.month} ${selectedTime.value.weekday}`
  dialogFormData.value.cronExpression = cron
  cronGeneratorVisible.value = false
}
// 确认提交
const confirm = async () => {
  if (isViewMode.value) {
    resetForm()
    return
  }

  // 表单验证
  if (!dialogFormData.value.taskName ||
    !dialogFormData.value.cronExpression ||
    !dialogFormData.value.startTime ||
    !dialogFormData.value.category) {
    ElMessage.error('请填写必填项')
    return
  }
  // 检查是否有选中的商品
  if (!inventoryDisplayRef.value.selectGoods || inventoryDisplayRef.value.selectGoods.length === 0) {
    ElMessage.error('请至少选择一项')
    return
  }

  // 根据是否有ID判断是新增还是更新
  // if (dialogFormData.value.id) {
  // await updateApi(dialogFormData.value)
  // } else {
  let res = await addTaskApi(dialogFormData.value)
  console.log(res)
  const addData = {
    category: dialogFormData.value.category,
    targetId: inventoryDisplayRef.value.selectGoods.length > 0 ? inventoryDisplayRef.value.selectGoods[0].id : null,
    stocktakingTaskId: res.data,
  }
  console.log('inventoryDisplayRef.value.selectGoods', inventoryDisplayRef.value.selectGoods)
  console.log('addData', addData)
  let rres = await addTaskDetailsApi(addData)
  if (res.code && rres.code) {
    ElMessage.success('操作成功')
    resetForm()
    emit('refresh')
  } else {
    ElMessage.error('操作失败: ' + error.message)
  }
}

defineExpose({
  dialogVisible,
  dialogFormData,
  isViewMode,
  resetForm,
  openCronGenerator,  // 暴露打开生成器的方法
  generateCron       // 暴露生成Cron的方法
})
</script>

<template>
  <InventoryDisplay ref="inventoryDisplayRef" :inventory-data="inventoryData" :title="getDialogTitle()" />
  <el-dialog v-model="dialogVisible" :title="isViewMode ? '查看盘点任务' : (dialogFormData.id ? '编辑盘点任务' : '新增盘点任务')"
    width="600px" :close-on-click-modal="false">
    <el-form :model="dialogFormData" :rules="rules" label-width="140px" :disabled="isViewMode">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="dialogFormData.taskName" placeholder="请输入任务名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行时间表达式" prop="cronExpression">
            <div style="display: flex; align-items: center;">
              <el-input v-model="dialogFormData.cronExpression" placeholder="请输入cron表达式" style="flex: 1;" />
              <el-button type="primary" size="small" style="margin-left: 10px;" @click="openCronGenerator">
                生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务执行时间" prop="startTime">
            <el-date-picker v-model="dialogFormData.startTime" type="datetime" placeholder="请选择任务执行时间"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点类型" prop="category">
            <el-select v-model="dialogFormData.category" placeholder="请选择盘点类型">
              <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="状态">
            <el-switch v-model="dialogFormData.isEnable" :active-value="1" :inactive-value="2" active-text="启用"
              inactive-text="停用" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="confirm">
          确定
        </el-button>
        <el-button v-else type="primary" @click="resetForm">
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="cronGeneratorVisible" title="生成Cron表达式" width="800px">
    <div style="padding: 20px;">
      <el-form :model="selectedTime" label-width="100px">
        <!-- 分钟 -->
        <el-form-item label="分钟">
          <el-input v-model.number="selectedTime.minute" placeholder="0-59" />
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <strong>示例：</strong>
            <br>• 0 = 每小时整点
            <br>• 30 = 每小时半点
            <br>• 15,45 = 每小时15分和45分
            <br>• */15 = 每15分钟一次
          </div>
        </el-form-item>

        <!-- 小时 -->
        <el-form-item label="小时">
          <el-input v-model.number="selectedTime.hour" placeholder="0-23" />
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <strong>示例：</strong>
            <br>• 0 = 凌晨0点
            <br>• 8 = 上午8点
            <br>• 17 = 下午5点
            <br>• 0-6 = 凌晨0点到早上6点
            <br>• */2 = 每2小时一次
          </div>
        </el-form-item>

        <!-- 日期 -->
        <el-form-item label="日期">
          <el-input v-model="selectedTime.day" placeholder="* 或 1-31" />
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <strong>示例：</strong>
            <br>• * = 每天
            <br>• 1 = 每月1号
            <br>• 15 = 每月15号
            <br>• 1-15 = 每月1-15号
            <br>• */3 = 每3天一次
          </div>
        </el-form-item>

        <!-- 月份 -->
        <el-form-item label="月份">
          <el-input v-model="selectedTime.month" placeholder="* 或 1-12" />
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <strong>示例：</strong>
            <br>• * = 每月
            <br>• 1 = 1月
            <br>• 6 = 6月
            <br>• 1-6 = 1-6月
            <br>• */3 = 每3个月一次
          </div>
        </el-form-item>

        <!-- 星期 -->
        <el-form-item label="星期">
          <el-input v-model="selectedTime.weekday" placeholder="* 或 0-7 (0=周日)" />
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <strong>示例：</strong>
            <br>• * = 每天
            <br>• 0 = 周日
            <br>• 1 = 周一
            <br>• 0-6 = 周日到周六
            <br>• 1-5 = 周一到周五
            <br>• 0,6 = 周六和周日
          </div>
        </el-form-item>

        <!-- 常用模板 -->
        <el-form-item label="常用模板">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <el-button type="text" size="small" @click="setTemplate('每天凌晨')">每天凌晨</el-button>
            <el-button type="text" size="small" @click="setTemplate('每天中午')">每天中午</el-button>
            <el-button type="text" size="small" @click="setTemplate('每周日')">每周日</el-button>
            <el-button type="text" size="small" @click="setTemplate('每月1号')">每月1号</el-button>
            <el-button type="text" size="small" @click="setTemplate('每小时')">每小时</el-button>
            <el-button type="text" size="small" @click="setTemplate('每3小时')">每3小时</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cronGeneratorVisible = false">取消</el-button>
        <el-button type="primary" @click="generateCron">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>